package com.ocl.www.security;

import java.util.*;

import javax.annotation.PostConstruct;

import com.ocl.www.controller.LoginController;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.subject.PrincipalCollection;

import org.springframework.beans.factory.annotation.Autowired;

import com.ocl.www.domain.MenuRole;
import com.ocl.www.domain.User;
import com.ocl.www.domain.UserRole;
import com.ocl.www.service.MenuRoleService;
import com.ocl.www.service.UserRoleService;
import com.ocl.www.service.UserService;

public class ShiroCasRealmImpl extends CasRealm {

	private static final Logger logger = Logger.getLogger(ShiroCasRealmImpl.class); //LoggerFactory.getLogger(ShiroCasRealmImpl.class.getSimpleName());
	
	@Autowired
	private UserService userService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private MenuRoleService menuRoleService;
	private Logger log = Logger.getLogger(ShiroCasRealmImpl.class);
	@PostConstruct
	public void initProperty () {
		setCasServerUrlPrefix(ShiroCasConfiguration.casServerUrlPrefix);
		//客户端回调地址
		setCasService(ShiroCasConfiguration.shiroServerUrlPrefix + ShiroCasConfiguration.casFilterUrlPattern);
		
	}

	/**
	 * 
	 * @Title: ShiroCasRealmImpl
	 * @Description: 权限认证
	 * @param: @param principalCollection
	 * @param: @return
	 * @throws
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		try {
			logger.info("##################执行Shiro权限认证##################");
		//获取当前登录输入的用户名，等价于(String) principalCollection.fromRealm(getName()).iterator().next();
		//String loginName = (String)super.getAvailablePrincipal(principalCollection);
//			Set<?> s = principalCollection.asSet();
//			Object[] obj = new Object[2];
//			int obji = 0;
//			Iterator<?> it = s.iterator();
//			while(it.hasNext()){
//				obj[obji] = it.next();
//				log.info(obj.getClass());
//				log.info(obj.toString());
//				obji++;
//			}
//			Map<String,String> map = (Map<String, String>) obj[1];
//			String userId = map.get("userId");
//
			String loginName = (String) super.getAvailablePrincipal(principalCollection);
			User loginUser = new User();
			loginUser.setUserName(loginName);
//			loginUser.setUserId(Integer.valueOf(userId));
//
//			//到数据库查是否有此对象
			User user = userService.findUserInfo(loginUser);
//			System.out.println(",loginName="+loginName+",UserId="+user.getUserId()+",UserName="+user.getUserName());
			UserRole userrole = new UserRole();
			userrole.setUsername(loginName);
			List<UserRole> urlist = userRoleService.selectUserRoles(userrole);
			Set<String> roleset = new HashSet<String>();
			for(int i = 0;i<urlist.size();i++){

				roleset.add(urlist.get(i).getRolename());

			}
			if (user != null) {
				//权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
				SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
				//用户的角色集合
				authorizationInfo.setRoles(roleset);

//				System.out.println("1234567890===========================");
				//用户的角色对应的所有权限，如果只使用角色定义访问权限，下面的四行可以不要
//				List<Role> roleList=user.getRoleList();
	            for (UserRole userroletemp : urlist) {
	            	MenuRole menurole = new MenuRole();
	            	menurole.setRoleid(userroletemp.getRoleid());
	            	List<MenuRole> mrlist = menuRoleService.selectMenuRoles(menurole);
	            	Set<String> mrset = new HashSet<String>();
	            	for(int i = 0;i<mrlist.size();i++){

	            		mrset.add(mrlist.get(i).getMenuname());

	    			}
	            	authorizationInfo.addStringPermissions(mrset);

	            }
				return authorizationInfo;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//返回null的话，就会导致任何用户访问被拦截的请求时，都会自动跳转到unauthorizedUrl指定的地址
		return null;


	}
}
